<?php
/**
 * 脑波检测仪接口控制器 继承A控制器，A控制器的控制接口秘钥登录
 */
namespace Api\Controller;
use Think\Controller;
class NbApiController extends AController {
    public function _empty(){
        echo '脑波接口访问地址错误';
    }
    //1.用户登录接口
    public function nb_login(){
        $name = I('login_name');
        $pass = I('password');
        $parame = array(
            'login_name'=>$name,
            'password'=>$pass
        );
        AddLog($parame,'用户登录');
        if(!$name || !$pass){
            $arr = array(
                'code'=>0,
                'msg'=>'参数错误(Parameter error)'
            );
            $this->ajaxReturn($arr);
        }
        //查询用户是否存在
        $w['name']=$name;
        $w['email']=$name;
        $w['phone']=$name;
        $w['_logic']='OR';
        $w_1['password']=$pass;
        $w_1['_complex']=$w;
        $res = M('user')->where($w_1)->find();
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'uid'=>$res['id'],
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'登录失败,账号或密码错误(Login failed,Account or password error)'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //获取所有机构名称列表
    public function nb_organization_lists(){
        $organizationArr = M('jggl')->field('group_id,jgqc')->select();
        //unset($organizationArr);
        if(empty($organizationArr)){
            //查询失败
            $code = 0;
            $msg = 'failed';
        }else{
            $code = 1;
            $msg = 'success';
        }
        //返回信息
        $arr = array(
            'code' => $code,
            'result'=>array(
                'msg' => $msg,
                'org_lists' => $organizationArr
            )
        );
        $this->ajaxReturn($arr);
    }
    //用户注册接口
    public function nb_register(){
        $data = I('post.');
        AddLog($data,'用户注册');
        $org_id        = I('org_id','','intval');
        $register_name = I('register_name');
        $register_form = I('register_form');
        $register_type = I('register_type');
        $password      = I('password');
        $re_password   = I('re_password');
        $verify_code   = I('verify_code');

        if(!$register_name || !$register_form || !$register_type || !$password || !$org_id){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $userinfo=array(
            'org_id'       =>$org_id,
            'register_form'=>$register_form,
            'register_type'=>$register_type,
            'password'     =>$password,
            'register_time'=>time(),
            'user_form'    =>1
        );
        if($register_type==1){
            $userinfo['name']=$register_name;
            //查询用户名是否已经被注册
            $w['name']=$userinfo['name'];
            $w['user_form']=1;
            $this->check_name_register($w);//验证用户名是否已经注册
        }elseif($register_type==2){
            $userinfo['phone']=$register_name;
            //这里验证手机号格式是否正确
            $this->check_phone($userinfo['phone']);
            //这里验证用户输入的手机验证码是否正确
            $this->check_verify($verify_code,$register_name,'phone');
        }elseif($register_type==3){
            //这里验证用户输入的邮箱验证码是否正确
            $userinfo['email']=$register_name;
            $this->check_email($userinfo['email']);
            //这里验证用户输入的邮箱验证码是否正确
            $this->check_verify($verify_code,$register_name,'email');
        }else{
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'register_type参数错误'
                )
            );
            $this->ajaxReturn($arr);
        }
        //验证两次输入的密码是否相同
        $this->check_password($password,$re_password);

        $uid = M('user')->add($userinfo);
        if($uid){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'uid'=>$uid
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'msg'=>'注册失败'
            );
        }
        $this->ajaxReturn($arr);
    }
    //用户手机获取验证码接口
    public function nb_phone_verify(){
        $phone = I('phone');
        $type  = I('type');
        if($type=='register'){
            //先查询手机号是否已经注册
            $w['phone']=$phone;
            $w['user_form']=1;
            $this->check_phone_register($w);//验证手机号是否已经注册
        }
        $res = $this->phone_verify($phone);
        if($res['code']==2){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    //'verify'=>$res['verify']
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'获取验证码失败（Failed to obtain verification code）',
                    //'verify'=>''
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //获取邮箱验证码接口
    public function nb_email_verify(){
        $email = I('email');
        $type  = I('type');
        if($type=='register'){
            //先查询邮箱是否已经注册
            $w['email']=$email;
            $w['user_form']=1;
            $this->check_email_register($w);//验证邮箱是否已经注册
        }
        $res = $this->email_verify($email);
        if($res['code']==1){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    //'verify'=>$res['verify']
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'邮箱验证码发送失败（Failed to obtain verification code）',
                    //'verify'=>''
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //用户信息查询接口
    public function nb_userinfo(){
        $uid = I('uid');
        //判断用户id是否正确
        $this->check_uid($uid);
        //判断数据库中是否有传入的id的用户
        $user = $this->check_user($uid);
        if($user['head_pic']){
            $head_pic=$user['head_pic'];
        }else{
            $head_pic='http://'.$_SERVER['HTTP_HOST'].C('HOME_IMAGE').'13.jpg';
        }
        $arr = array(
            'code'=>1,
            'ressult'=>array(
                'msg'=>'success',
                'userinfo'=>array(
                    'username'=>$user['name'],
                    'head_pic'=>$head_pic,
                    'phone'   =>$user['phone'],
                    'email'  =>$user['email'],
                    'nickname'=>$user['nickname'],
                    'birthday'=>$user['birthday'],
                    'sex'     =>$user['sex'],
                    'register_form'=>$user['register_form']
                )
            )
        );
        $this->ajaxReturn($arr);
    }

    //修改用户信息接口
    public function nb_userinfo_update(){
        $data = array(I('post.'),$_FILES['head_pic']);
        AddLog($data,'修改用户信息接口nb_userinfo_update');
        $file = $_FILES['head_pic']['name'];
        if($file){
            $file = explode('.',$file);
            $count = count($file);
            $str = $file[$count-1];
            if($str != 'gif' && $str !='png' && $str != 'jpeg' && $str != 'jpg'){
                $res = array(
                    'code'=>0,
                    'result'=>array(
                        'msg'=>'请上传gif、png、jpeg或jpg格式图片'
                    )
                );
                $this->ajaxReturn($res);
            }
            $upload = new \Think\Upload();// 实例化上传类
            $upload->exts = array('gif','png','jpg','jpeg');  //设置文件格式
            $upload->maxSize   =     5485760 ;// 设置附件上传大小5M
            $upload->savePath  =  '/User_head_IMG/'; // 设置附件上传目录
            $info   =   $upload->uploadOne($_FILES['head_pic']);// 上传文件
            if(!$info){
                $arr = array(
                    'code'=>0,
                    'result'=>array(
                        'msg'=>'用户头像上传失败'
                    )
                );
                $this->ajaxReturn($arr);
            }
            $head_pic='http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Uploads'.$info['savepath'].$info['savename'];
        }
        $sex = I('sex');
        //判断用户sex传入是否正确
        if($sex && intval($sex) != 2 && intval($sex) != 1){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'sex参数错误,只能是1或2(sex Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $data = array(
            'id'      =>I('uid'),
            'birthday'=>I('birthday'),
            'nickname'=>I('nickname'),
            'sex'     =>I('sex'),
            'head_pic'=>$head_pic
        );
        $data = array_filter($data);
        //判断用户id是否正确
        if(!$data){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'参数错误(Parameter error)'
                )
            );
            $this->ajaxReturn($arr);
        }

        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'修改失败(Modify failed)'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //修改手机号
    public function nb_update_phone(){
        AddLog(I('post.'),'修改手机号nb_update_phone');
        $uid    = I('uid');
        //检查uid是否正确
        $this->check_uid($uid);
        $phone  = I('phone');
        $verify = I('code');
        //判断手机号是否正确
        $this->check_phone($phone);
        //判断验证码是否正确
        $this->check_verify($verify,$phone,'phone');
        $data = array(
            'id'=>$uid,
            'phone'=>$phone
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //修改邮箱
    public function nb_update_email(){
        AddLog(I('post.'),'修改邮箱nb_update_email');
        $uid    = I('uid');
        //检查uid是否正确
        $this->check_uid($uid);
        $email  = I('email');
        $verify = I('code');
        //判断邮箱是否正确
        $this->check_email($email);
        //判断验证码是否正确
        $this->check_verify($verify,$email,'email');
        $data = array(
            'id'=>$uid,
            'email'=>$email
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //修改密码
    public function nb_update_password(){
        AddLog(I('post.'),'修改密码nb_update_password');
        $uid    = I('uid');
        //检查uid是否正确
        $this->check_uid($uid);
        $password= I('password');
        $phone  = I('phone');
        $verify = I('code');
        //判断手机号是否正确
        $this->check_phone($phone);
        //判断验证码是否正确
        $this->check_verify($verify,$phone,'phone');
        $data = array(
            'id'=>$uid,
            'password'=>$password
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //用户未登陆修改密码
    public function reset_password_byphone(){
        AddLog(I('post.'),'修改密码nb_update_password_beforelogin');
        $password= I('password');
        $phone  = I('phone');
        $verify = I('code');
        //判断手机号是否正确
        $this->check_phone($phone);
        //判断验证码是否正确
        $this->check_verify($verify,$phone,'phone');
        $data = array(
            'phone'=>$phone,
            'password'=>$password
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //用户未登陆修改密码
    public function reset_password_byemail(){
        AddLog(I('post.'),'修改密码nb_update_password_beforelogin');
        $password= I('password');
        $email  = I('email');
        $verify = I('code');
        //判断邮箱是否正确
        $this->check_email($email);
        //判断验证码是否正确
        $this->check_verify($verify,$email,'email');
        $data = array(
            'email'=>$email,
            'password'=>$password
        );
        $res = M('user')->save($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //每20秒传输一次实时的脑波数据
    public function nb_upload_EEG_data(){
        $uid = I('uid');//用户id
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $exam_result=I('exam_result');//测试数据
        $exam_result=html_entity_decode($exam_result);
        $data = array(
            'uid'=>$uid,
            'exam_result'=>$exam_result,
            'upload_time'=>time()
        );
        AddLog($data,'每20秒上传一次脑波数据');
        M('exam_result')->add($data);
        //$exam_result='[ {"timeStamp":"2016-12-12 12:23:12", "hightbeta" : [ 27780, 19552, 17308, 10569, 6663, 15210, 31499, 26118, 11258, 19476, 9392, 6166, 12527, 477, 6163, 44623, 12986, 13598, 36727, 34780 ], "lowbeta" : [ 26242, 18176, 20796, 4015, 10940, 10459, 25724, 40846, 35638, 68778, 16465, 7436, 19122, 2985, 5618, 12911, 10945, 14067, 33201, 30453 ], "lowgamma" : [ 9249, 18782, 8967, 3015, 4811, 24490, 22753, 16787, 16325, 14305, 25804, 1577, 12372, 1212, 5398, 13581, 19163, 8592, 34233, 22315 ], "theta" : [ 140115, 321062, 92346, 76360, 29812, 68347, 165375, 274384, 530699, 39323, 109495, 21420, 129715, 10993, 19259, 28008, 108371, 109313, 104030, 321638 ], "Attention" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "lowalpha" : [ 30133, 16707, 35592, 8978, 2335, 88285, 32756, 9059, 25882, 22339, 6735, 6405, 25500, 1350, 5950, 47288, 2803, 34567, 31363, 157345 ], "highalpha" : [ 18725, 45479, 15356, 4739, 5778, 43543, 33503, 82160, 15992, 14833, 15720, 4679, 26783, 965, 2581, 16746, 28439, 8225, 10758, 44113 ], "delta" : [ 434487, 880768, 834296, 395021, 547634, 953735, 259493, 1002872, 760030, 1304871, 1317960, 299958, 1278488, 229482, 171063, 998740, 477383, 801304, 278421, 1317306 ], "index" : 1, "singel" : [ 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200 ], "Meditation" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "highgamma" : [ 22853, 13574, 17524, 4943, 2678, 13000, 8613, 19648, 6226, 3755, 9475, 1914, 3614, 269, 3655, 10114, 6700, 21646, 15456, 11520 ] } ]';
        $exam_info = json_decode($exam_result);
        $exam_info = $exam_info['0'];
        foreach ($exam_info as $key=>$val){
            if($key=='index'){
                $exam_data[$key]=$val;
            }elseif($key=='timeStamp'){
                $exam_data['timeStamp']=strtotime($val);
            }else{
                $exam_data[$key]=implode(',',$val);
            }
        }
        //查询表中最大的检查次数值
        $last_data = M('exam_result_copy')->where('uid='.$uid)->max('num');
        if ($last_data){
            $num = $last_data;
        }else{
            $num = 0 ;
        }
        if($exam_data['index']==1){
            $num += 1;
        }
        $exam_data['uid']=$uid;
        $exam_data['num']=$num;
        $exam_data['time']=time();
        $res = M('exam_result_copy')->add($exam_data);

        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //检测完毕后，传输一次完整的原始数据
    public function nb_upload_file_data(){
        $uid = I('uid');//用户id
        $_FILES['uid']=$uid;
        AddLog($_FILES,'上传脑波文件');
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $file = $_FILES['file_name']['name'];
        $file = explode('.',$file);
        $count = count($file);
        $str = $file[$count-1];
        if($str != 'txt'){
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'请先上传TXT文件'
                )
            );
            $this->ajaxReturn($res);
        }
        $upload = new \Think\Upload();// 实例化上传类
        $upload->exts = array('txt');  //设置文件格式
        $upload->maxSize   =     41943040 ;// 设置附件上传大小40M
        $upload->savePath  =  '/Nb_data/'; // 设置附件上传目录
        $info   =   $upload->uploadOne($_FILES['file_name']);// 上传文件

        if (!$info) {
            $res = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'上传TXT文件失败'
                )
            );
            $this->ajaxReturn($res);
        }else{
            $data = array(
                'uid'=>$uid,
                'file_name'=>$info['name'],
                'upload_time'=>time(),
                'size'=>$info['size'],
                'md5'=>$info['md5'],
                'sha1'=>$info['sha1'],
                'url'=>'http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Uploads'.$info['savepath'].$info['savename']
            );
            $res = M('exam_file')->add($data);
            if($res){
                $arr = array(
                    'code'=>1,
                    'result'=>array(
                        'msg'=>'success',
                        'info'=>$data
                    )
                );
            }
            $this->ajaxReturn($arr);
        }
    }
    //获取移动设备信息接口
    public function nb_get_mobile_information(){
        $ip_address = get_client_ip();
        import('Org.Net.IpLocation');// 导入IpLocation类
        $Ip = new \IpLocation('UTFWry.dat'); // 实例化类 参数表示IP地址库文件
        $area = $Ip->getlocation($ip_address); // 获取某个IP地址所在的位置
        //echo '<pre>';
        //print_r($area);exit;
        $ip_city = $area['country'];
        $data = array(
            'equipment_id'=>I('equipment_id'),
            'platform'=>I('platform'),
            'sys_version'=>I('sys_version'),
            'equipment_name'=>I('equipment_name'),
            'ip_address'=>$ip_address,
            'ip_city'=>$ip_city,
            'time'=>time()
        );
        AddLog($data,'添加移动设备信息');
        $res = M('mobile_equipment')->add($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'faild'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //外接蓝牙设备信息接口
    public function nb_get_bluetooth_information(){
        $data = array(
            'bluetooth_information'=>I('bluetooth_information'),
            'time'=>time()
        );
        AddLog($data,'外接蓝牙设备信息');
        $res = M('bluetooth_equipment')->add($data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'fail'
                )
            );
        }
        $this->ajaxReturn($arr);
    }
    //查询用户的完整脑波检测原始数据的接口
    public function nb_user_EEG_data_list(){
        $uid = I('uid');
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $res = M('exam_file')->where('uid='.$uid)->select();
        //查询num的值
        $num_arr = M('exam_result_copy')->field('num')->where('uid='.$uid)->group('num')->order('num desc')->select();
        foreach ($res as $key=>$val){
            $maxnum = $num_arr[$key]['num'];
            $result_copy = M('exam_result_copy')->where('uid='.$uid.' and num='.$maxnum)->select();
            $data = array();
            foreach ($result_copy as $val){
                $data['id'] =$val['id'];
                $data['uid'] =$val['uid'];
                $data['num'] =$val['num'];
                $data['time'] =$val['time'];
                $data['hightbeta'] .= $val['hightbeta'].',';
                $data['lowbeta'] .= $val['lowbeta'].',';
                $data['lowgamma'] .=$val['lowgamma'].',';
                $data['theta'] .=$val['theta'].',';
                $data['attention'] .=$val['attention'].',';
                $data['lowalpha'] .=$val['lowalpha'].',';
                $data['highalpha'] .=$val['highalpha'].',';
                $data['delta'] .=$val['delta'].',';
                $data['singel'] .=$val['singel'].',';
                $data['meditation'] .=$val['meditation'].',';
                $data['highgamma'] .=$val['highgamma'].',';
            }
            $res[$key]['detection_result']=$data;
        }
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    'info'=>$res
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'faild'
                )
            );
        }
        //echo json_encode($arr);
        $this->ajaxReturn($arr);
    }
    //返回完整脑波数据接口
    public function nb_download_EEG_data(){
        $id = I('id');
        if(!is_numeric($id)){
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'请输入正确的id(Please enter the correct uid)'
                )
            );
            $this->ajaxReturn($arr);
        }
        $w = array(
            'id'=>$id
        );
        $file = M('exam_file')->where($w)->find();
        if($file){

            $url = $file['url'];
            /* $path = getcwd();
            $path = str_replace('\\','/',$path);
            $data = $path.'/Uploads'.$url;
            $info = file_get_contents($data); */
            //$fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5','ANSI')) ;
            //if( $fileType != 'UTF-8'){
            //    $info = iconv('gbk', 'utf-8', $info);
            //}
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success',
                    //'info'=>base64_encode($info)
                    'info'=>'',
                    'file_url'=>$url,
                    'sha1'=>$file['sha1'],
                )
            );
        }else{
            $arr = array(
                'code'=>0,
                'result'=>array(
                    'msg'=>'faild'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //下载脑波数据接口以CSV格式输出
    public function nb_download_EEG_data_csv(){
        $uid = I('uid');
        $fp = fopen("Uploads/NB_data/csv.csv","w"); //打开csv文件，如果不存在则创建

        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $w = array(
            'id'=>$uid
        );
        //查询用户信息
        $user = M('user')->where($w)->find();
        //查询$uid的检测次数
        $num_arr = M('exam_result_copy')->field('num')->where('uid='.$uid)->group('num')->order('id desc')->select();
        $count = M('exam_result_copy')->field('id')->where('uid='.$uid)->group('num')->select();
        $count = count($count);
        $data_str='用户id,昵称,用户名,手机号,邮箱,检测次数,上传时间,timeStamp（检测时间）,hightbeta,lowbeta,lowgamma,theta,attention,lowalpha,highalpha,delta,singel,meditation,highgamma'."\r\n";
        foreach ($num_arr as $key=>$val){
            //查询num等于$maxnum 的数据
            $result_copy = M('exam_result_copy')->where('uid='.$uid.' and num='.$val['num'])->select();
            $data = array();
            foreach ($result_copy as $val){
                $data['uid'] =$val['uid'];
                $data['nickname']=$user['nickname'];
                $data['name']=$user['name'];
                $data['phone']=$user['phone'];
                $data['email']=$user['email'];
                $data['num'] =$val['num'];
                $data['time'] =date('Y-m-d H:i:s',$val['time']);
                $data['timeStamp'] =date('Y-m-d H:i:s',$val['timeStamp']);
                $data['hightbeta'] .= str_replace(',',';',$val['hightbeta']).';';
                $data['lowbeta'] .= str_replace(',',';',$val['lowbeta']).';';
                $data['lowgamma'] .= str_replace(',',';',$val['lowgamma']).';';
                $data['theta'] .= str_replace(',',';',$val['theta']).';';
                $data['attention'] .= str_replace(',',';',$val['attention']).';';
                $data['lowalpha'] .= str_replace(',',';',$val['lowalpha']).';';
                $data['highalpha'] .= str_replace(',',';',$val['highalpha']).';';
                $data['delta'] .= str_replace(',',';',$val['delta']).';';
                $data['singel'] .= str_replace(',',';',$val['singel']).';';
                $data['meditation'] .= str_replace(',',';',$val['meditation']).';';
                $data['highgamma'] .= str_replace(',',';',$val['highgamma']).';';

            }
            $data_str .= implode(',',$data)."\r\n"; //加入换行符
        }
        /*
        $data_arr1 = array("10001","10002","10003","10004","公司"); //第一行数据
        $data_arr2 = array("20001","20002","20003","20004","中午"); //第二行数据
        $data_str1 = implode(",",$data_arr1); //用 ' 分割成字符串
        $data_str2 = implode(",",$data_arr2); //用 ' 分割成字符串
        $data_str = $data_str1."\r\n".$data_str2."\r\n"; //加入换行符
          */
        fwrite($fp,iconv('UTF-8','GB2312',$data_str)); //写入数据
        fclose($fp); //关闭文件句柄
        $arr = array(
            'code'=>1,
            'result'=>array(
                'msg'=>'success',
                'file_url'=>'http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/Uploads/NB_data/csv.csv',
            )
        );
        $this->ajaxReturn($arr);
    }

    //接收上传的音乐脑波数据
    public function nb_upload_music_EEG_data(){
        $uid = I('uid');//用户id
        //判断uid是否输入正确
        $this->check_uid($uid);
        //查询数据库中是否有该用户
        $this->check_user($uid);
        $exam_result=I('exam_music_result');//测试数据
        $exam_result=html_entity_decode($exam_result);
        $data = array(
            'uid'=>$uid,
            'exam_result'=>$exam_result,
            'upload_time'=>time()
        );
        AddLog($data,'上传的音乐脑波数据');
        M('exam_music_result')->add($data);
        $exam_data['uid'] = $uid;
        $exam_data['upload_time']=time();
        $exam_info = json_decode($exam_result);
        $exam_info = $exam_info['0'];
        foreach ($exam_info as $key=>$val){
            if($key == 'musicIndex' || $key=='musicName' || $key=='outTime' || $key=='scene' || $key=='instrument' || $key=='enterTime'){
                $exam_data[$key]=$val;
            }else{
                $exam_data[$key]=implode(',',$val);
            }
        }
        //查询表中最大的检查次数值
        $last_data = M('exam_music_result_copy')->where('uid='.$uid)->max('num');
        if ($last_data){
            $num = $last_data;
        }else{
            $num = 0 ;
        }
        if($exam_data['musicIndex']==1){
            $num += 1;
        }
        $exam_data['num']=$num;
        $res = M('exam_music_result_copy')->add($exam_data);
        if($res){
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'success'
                )
            );
        }else{
            $arr = array(
                'code'=>1,
                'result'=>array(
                    'msg'=>'failed'
                )
            );
        }
        $this->ajaxReturn($arr);
    }

    //上传调查报告数据
    public function upload_survey_data(){
        $uid = I('uid');
        $time = date('YmdHis');
        $form_type = $_POST['form_type'];
        $json_data = json_encode($_POST);
        $data = array(
            'uid'=>$uid,
            'time'=>$time,
            'json_data'=>$json_data,
            'form_type'=>$form_type
        );
        $res = M('survey_data')->add($data);
        //echo $res;
        if($res){
            $arr=array(
                'code'=>1,
                'msg'=>'上传数据成功'
            );
            $this->ajaxReturn($arr);
        }else{
            $arr=array(
                'code'=>0,
                'msg'=>'上传数据失败'
            );
            $this->ajaxReturn($arr);
        }
    }

}
